from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import Resource,Api
from utils.Myredis import r
from utils.captcha.captcha import captcha
from utils.Myredis import r
import json
from utils.comm import send_message
import random
from application.models.users.user import *
from application.models.users.user import db
from db import db
import time
from utils.Myjwt import myjwt
import functools,time
goods_blue=Blueprint("goods",__name__)
api=Api(goods_blue)

# 获取类别
# @goods_blue.route("/gettype")
def gettype():
    sql = "select * from  ctype"
    res = db.findAll(sql)
    return res
    # res=r.get_str("typelist")
    # if res:
    #     res=json.loads(res)
    #     print("缓存")
    # else:
    #     types=Ctype.query.all()
    #     lst=[]
    #     for i in types:
    #         lst.append({
    #             "id": i.id,
    #             "name": i.name
    #         })
    #     # r.add_str("typelist",json.dumps(lst))
    #     # print("数据库")
    #     return jsonify({"code":200,"msg":"ok","lst":lst})
# 获取标签
# @goods_blue.route("/gettag")
def gettag():
    sql = 'select * from tags'
    res = db.findAll(sql)
    return res
    # res=r.get_str("taglist")
    # if res:
    #     res=json.loads(res)
    #     print("缓存")
    # else:
    #     res=Tags.query.all()
    #     lst=[]
    #     for i in res:
    #         lst.append({
    #             "id":i.id,
    #             "status":i.status,
    #             "name":i.name
    #         })
    #     # r.add_str("taglist",json.dumps(lst))
    #     return jsonify({"code":200,"msg":"ok","lst":lst})
# 获取课程信息
def getcourse(page):
    page_size=2
    # 查询缓存 如果存在直接返回
    key="home"+str(page)
    courselist=r.get_str(key)
    if courselist:
        courselist=json.loads(courselist)
    else:
        # 获取指定页数据
        start = (int(page) - 1)* page_size
        print("ttttttt",type(start))
        # 并发访问同时操作数据库 解决方案分布式锁
        flag=r.str_setnx(key+"setnx",1)
        if flag==True:
            sql1 = "select * from course limit %d,%d" % (int(start), page_size)
            lst=db.findAll(sql1)
            # 存在redis  decimal float  datetime 时间日期类型
            courselist=[]
            for i in lst:
                i["create_time"]=datetime.datetime.strftime(i["create_time"],"%Y-%m-%d %H:%M:%S")
                courselist.append(i)
            r.add_str(key,json.dumps(courselist))
            # 释放锁
            r.del_key(key+"setnx")
    sql="select count(id) as t from course"
    res=db.findone(sql)
    total=res["tcount"]
    # 指定每页显示多少条
    return courselist,total,page_size
#获取首页课程分类及课程信息
@goods_blue.route("/home")
def home():
    # 获取当前页
    page=request.args.get("page")
    # 获取类型
    types=gettype()
    # 获取标签
    tags=gettag()
    # 获取课程
    courselist,total,page_size=getcourse(page)
    return jsonify({"code":200,'typelist':types,"taglist":tags,"clist":courselist,"total":total,"page_size":page_size})
# 多条件查询
# 获取首页课程分类及课程信息
@goods_blue.route("/getHomeCourse")
def getHomeGourse1():
    # 获取类型
    typelist = gettype()
    # 获取标签
    taglist = gettag()

    # 获取当前页面
    page = request.args.get("page")
    # 获取查询条件
    tagid = request.args.get("tagid")
    typeid=request.args.get("type")
    where=" "
    if int(typeid)>0:
        where=where+"and c.ctype="+typeid
    if int(tagid) > 0:
        tsql = "select count(c.id) as tcount from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
        sql = "select * from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
    else:
        sql = "select * from course as c  where 1=1"
        tsql = "select count(c.id) as  tcount from course as c  where 1=1"
    if where:
        sql=sql+" "+where
        tsql=tsql+" "+ where
    # 查询总共有多少条
    res = db.findone(tsql)
    total = res['tcount']
    page_size = 2
    start = (int(page) - 1)*page_size
    sql = sql + " limit %d,%d" % (start, page_size)
    courselist = db.findAll(sql)
    print(sql)
    return jsonify({"code": 200, "typelist": typelist, 'taglist': taglist, 'courselist': courselist, "total": total, "page_size": page_size})
# 课程详情页面
@goods_blue.route("/detail")
def detail():
    id=request.args.get("id")
    sql="select c.id,j.id as jid ,c.descrip,j.url,j.courseid,j.name,c.tcount from course as c inner join jie as j on c.id=j.courseid where c.id=%d"%(int(id))
    res=db.findAll(sql)
    lst=[]
    for i in res:
        lst.append({
            "id":i["id"],
            "name":i["name"],
            "url":i["url"],
            "courseid":i["courseid"]
        })
    clist={"id":res[0]["id"],"tcount":res[0]["tcount"],"url":res[0]["url"],"descrip":res[0]["descrip"]}
    return jsonify({"code":200,"jie":lst,"clist":clist})
@goods_blue.route("/getVideo")
def getVideo():
    courseid=request.args.get("courseid")
    userid=request.args.get("userid")
    id=request.args.get("id")
    sql="select level from user where id=%d"%(int(userid))
    user=db.findone(sql)
    ctype=user["ctype"]
    if int(ctype)==2:
        # 会员可看
        if int(user["type"])!=2:
            return jsonify({"code":401,"msg":"此用户无权观看"})
    